package cn.sh.tools.service.component.wechat;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.sh.tools.domain.constant.CommonConstant;
import cn.sh.tools.domain.constant.WeChatConstant;
import cn.sh.tools.domain.constant.WeChatMsgEnum;
import cn.sh.tools.domain.dto.WcMsgPutDto;
import cn.sh.tools.domain.vo.WcDepartmentVo;
import cn.sh.tools.domain.vo.WcStaffVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.stream.Collectors;

@Component
@Slf4j
public class BusinessWeChatComponent {

    @Autowired
    private BusinessWeChatService businessWeChatService;

    /**
     * 消息推送（目前只支持文本消息推送）
     *
     * @param departmentId 部门编号
     * @param msgContent   消息内容
     */
    public void msgPut(String departmentId, String msgContent) {
        // 1- 获取 接口凭证 AccessToken
        String accessToken = this.businessWeChatService.judgeWeChatCommonCacheAvailable(WeChatConstant.Token.ACCESS_TOKEN_CACHE_KEY);

        // 2- 获取部门成员信息
        if (StrUtil.isBlank(departmentId)) {
            // 当部门编号为空时，默认给“2”（天涯共此时）
            departmentId = "2";
        }
        WcDepartmentVo wcDepartmentVo = this.businessWeChatService.getWcDepartmentStaffInfo(accessToken, departmentId, CommonConstant.YES, WeChatConstant.CYCLE);
        if (Objects.isNull(wcDepartmentVo) || CollUtil.isEmpty(wcDepartmentVo.getUserlist())) {
            return;
        }
        // 部门成员编号集合
        String userIds = wcDepartmentVo.getUserlist().stream()
                .map(WcStaffVo::getUserid)
                .collect(Collectors.joining(WeChatConstant.PARAM_SEPARATE));

        // 3- 消息推送
        WcMsgPutDto wcMsgPutDto = new WcMsgPutDto();
        wcMsgPutDto.setTouser(userIds);
        wcMsgPutDto.setMsgtype(WeChatMsgEnum.TEXT.getMsgType());
        wcMsgPutDto.setAgentid(Integer.valueOf(this.businessWeChatService.judgeWeChatCommonCacheAvailable(WeChatConstant.AGENT_ID)));
        WcMsgPutDto.Text text = new WcMsgPutDto.Text();
        text.setContent(msgContent);
        wcMsgPutDto.setText(text);
        this.businessWeChatService.msgPut(accessToken, wcMsgPutDto, WeChatConstant.CYCLE);
    }

}
